package self.Lunastic.HexaSweeper.Object;

import self.Lunastic.HexaSweeper.Manager.FrameManager;
import self.Lunastic.HexaSweeper.Manager.GameManager;

/**
 * 格子群对象
 */
public class GameArea {
    // 雷区
    private int _sweeperSize;
    private int _bomberPercent;
    private GameCeil[][] _data;
    public void setCeil(GameCeil c, int x, int y){ this._data[x][y] = c; }
    public GameCeil getCeil(int x, int y){ return this._data[x][y]; }
    public GameCeil[][] getData (){return this._data;}

    // 初始化
    public void areaInit(){
        this._sweeperSize = GameManager.getSweeperSize();
        this._bomberPercent = GameManager.getBomberPercent();
    }

    // 生成格子数据
    public void createCeil(){
        int ss = this._sweeperSize;
        int minSize = Math.min(FrameManager.jFrame.getWidth(), FrameManager.jFrame.getHeight());
        int cr = (minSize / (ss*4-2) + 1);
        this._data = new GameCeil[ss*2-1][ss*2-1]; // 初始化格子群
        for (int i = 0; i < ss*2-1; i++) {
            for (int j = 0; j < ss*2-1; j++) {
                // 添加格子识别
                boolean isCeil = (i+j) >= (ss - 1) && (i+j) <= (ss * 3 - 3);
                GameCeil c = new GameCeil(i, j, cr, isCeil);
                this.setCeil(c, i, j);

                // 相邻格子互相添加标识
                if(i > 0 && isCeil){
                    this.getCeil(i - 1, j).aroundCeil.add(c);
                    c.aroundCeil.add(this.getCeil(i - 1, j));
                    if(j < ss * 2 - 2){
                        this.getCeil(i - 1, j + 1).aroundCeil.add(c);
                        c.aroundCeil.add(this.getCeil(i - 1, j + 1));
                    }
                }
                if(j > 0 && isCeil){
                    this.getCeil(i, j - 1).aroundCeil.add(c);
                    c.aroundCeil.add(this.getCeil(i, j - 1));
                }
            }
        }
    }

    // 生成炸弹
    public void createBomber(int x, int y){
        int ss = this._sweeperSize;
        int bp = this._bomberPercent;
        int bc = (3*ss*ss-3*ss+1)*bp/100; // bomber count
        while (bc > 0){
            int i = (int) (Math.random() * (ss*2-1));
            int j = (int) (Math.random() * (ss*2-1));
            if(i==x&&j==y) continue;
            GameCeil ceil = this.getCeil(i,j);
            if(ceil.isCeil() && ceil.getType()<-1){
                ceil.setType(-1);
                bc --;
            }
        }
        // 计算非雷区的计数
        for (GameCeil[] i:this._data) {
            for (GameCeil j:i) {
                if(j.isCeil() && j.getType() == -2){
                    int count = 0;
                    for (GameCeil c: j.aroundCeil) {
                        if(c.getType() == -1) count++;
                    }
                    j.setType(count);
                }
            }
        }
    }
}

